"use strict";

const Controller = require("egg").Controller;

const dayjs = require("dayjs");

class ArticleController extends Controller {
  async index() {
    const { ctx, app } = this;

    const {
      current = null,
      size = null,
      title = "",
      status = "",
      classify = "",
    } = ctx.request.body;

    let sql = " ";

    if (title) {
      sql += `where title = "${title}" `;
    } else if (status) {
      sql += `where status = "${status}" `;
    } else if (classify) {
      sql += `where classify = "${classify}" `;
    }

    let limit = ` limit ${(current - 1) * size} , ${size}`;

    const data = await app.mysql.query(`select * from article ` + sql + limit);

    const total = (
      await app.mysql.query(`select count(*) as count from article` + sql)
    )[0].count;

    ctx.body = {
      code: 1,
      data,
      total,
    };
  }

  async del() {
    const { ctx, app } = this;

    const { id } = ctx.request.body;

    const multipleSelection = ctx.request.body;

    if (id) {
      await app.mysql.delete("article", { id });
    }

    if (multipleSelection.length) {
      multipleSelection.forEach(async (item) => {
        await app.mysql.delete("article", { id: item.id });
      });
    }

    ctx.body = {
      code: 1,
      msg: "删除成功",
    };
  }

  async add() {
    const { ctx, app } = this;

    const {
      title,
      txt,
      password = "",
      classify = "",
      digest = "",
      pay = "",
      recommend = "",
      review = "",
      tag = "",
    } = ctx.request.body;

    await app.mysql.insert("article", {
      title,
      txt,
      password,
      classify,
      digest,
      pay, // 是否付费
      recommend, // 首页推荐
      review,
      tag,
      createtime: dayjs(new Date().getTime()).format("YYYY-MM-DD HH:mm:ss"),
      year: new Date().getFullYear(),
      mouth: new Date().getMonth() + 1,
    });

    ctx.body = {
      code: 1,
      msg: "发布成功",
    };
  }

  async recommend() {
    const { ctx, app } = this;

    const data = await app.mysql.select("article");

    ctx.body = {
      code: 1,
      data: data.filter((item) => {
        return item.recommend;
      }),
    };
  }

  async detail() {
    const { ctx, app } = this;

    const { id } = ctx.request.body;

    console.log(id);

    const data = await app.mysql.query(
      `select * from article where id = ${id * 1}`
    );

    ctx.body = {
      code: 1,
      data: data[0],
    };
  }
}

module.exports = ArticleController;
